package com.crc.luojian.util;

import com.crc.luojian.constant.DBProperties;

import java.io.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.List;
import java.util.Properties;
import java.util.Vector;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @program: luojian-springframework
 * @description:
 * @author: luojian58
 * @create: 2021-06-14 10:34
 */
public class DBConnectionPool {
    // 使用线程安全的集合 空闲线程 没用被使用的连接存放
    private List<Connection> freeConnection = new Vector<Connection>();
    // 使用线程安全的集合 活动线程 容器正在使用的连接
    private List<Connection> activeConnection = new Vector<Connection>();
    private static DBProperties dbProperties;
    final AtomicInteger atomicInteger = new AtomicInteger(0);
    int correntCount;
    static {
        //1 加载配置文件 初始化BDproperties
        try {
            Properties properties = loadProperties("db.properties");
            dbProperties = new DBProperties(properties);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public DBConnectionPool(){
        for(int i = 0;i < dbProperties.getInitConnections();i++){
            Connection connection = newConnection();
            if(connection != null){
                //放到空闲连接池中
                freeConnection.add(connection);
            }
        }
    }



    private static Properties loadProperties(String s) throws IOException {
        ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
        String path = contextClassLoader.getResource(s).getPath();
        Properties properties = new Properties();
        properties.load(new InputStreamReader
                (new FileInputStream(new File(path))));
        return properties;
    }

    public synchronized  Connection getConnection() {
        Connection connection = null;
        if (correntCount < dbProperties.getMaxActiveConnections()) {
            // 当前创建的线程<最大连接数
            // 判断空闲线程是否有数据
            if (freeConnection.size() > 0) {
                // 拿到再删除 freeConnection.get(0); freeConnection.remove(0);
                connection = freeConnection.remove(0);
            } else {
                connection = newConnection();
            }
            // 判断线程是否可用
            boolean available = isAvailable(connection);
            if (available) {
                activeConnection.add(connection);
            } else {
                correntCount--;
                connection = getConnection();// 重试 递归算法
            }
        } else {
            // 当前创建的线程>最大连接数
            try {
                wait(dbProperties.getConnTimeOut());
                connection = getConnection();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return connection;
    }
    private synchronized  Connection newConnection() {
        try {
            Class.forName(dbProperties.getDriverName());
            Connection connection = DriverManager.getConnection(dbProperties.getUrl(), dbProperties.getUserName(),
                    dbProperties.getPassword());
            correntCount = atomicInteger.incrementAndGet();
            return connection;

        } catch (Exception e) {
            return null;
        }
    }
    public boolean isAvailable(Connection connection) {
        try {
            if (connection == null || connection.isClosed()) {
                return false;
            }
        } catch (Exception e) {
             e.printStackTrace();
        }
        return true;
    }
    public synchronized void releaseConnection(Connection connection){
        try {
            // 判断连接是否可用
            if (isAvailable(connection)) {
                // 判断空闲线程是否已满
                if (freeConnection.size() < dbProperties.getMaxConnections()) {
                    freeConnection.add(connection);// 回收连接
                } else {
                    // 空闲线程满
                    connection.close();
                }

            }
            activeConnection.remove(connection);
            correntCount--;
            notifyAll();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
